#!/bin/bash

#****************************************************
# don't need modify
# user help for print
helpMe(){
    sed -rn 's/^### ?//;T;p;' "$0"
}

if [ "$1" == "" -o "$1" == "-h" -o "$1" == "-help" ]; then
    helpMe
    exit 1
fi
#****************************************************
###  
### Usage:
### ./tools/sign_tool_e3/run_sign_safe <board> <core> ... <core> 
###  
### Options:
###     <board>  the target board  eg:E3_z1/E3_evb/E3_ref
###     <core>   the target core, sf core is must 
###                   eg:sf/sp/sp0/sp1/sx/sx0/sx1
###

SIGN_CMD="./sign_tool/linux/atb_signer"
SIGNER_KEY="./sign_tool/keys/TestRSA2048_ossl.pem"

#****************************************************
if [ -L $0 ]
then
    BASE_DIR=`dirname $(readlink $0)`
else
    BASE_DIR=`dirname $0`
fi

#root_path=$(readlink -f .)
#echo ${root_path}
#IMG_DIR=${root_path}/build/$1
#echo $IMG_DIR

if [ -L $1 ]
then
    FilePath=`dirname $(readlink $1)`
else
    FilePath=`dirname $1`
fi

# Obtain file path
FilePath=$(echo "$FilePath" | sed 's/\\/\//g')

# Obtain file name
FileName=$(basename "$1" | sed 's/.bin$//')
echo "FilePath: $FilePath"
echo "FileName: $FileName"
SIGNED_IMAGE=$(basename "$1")

SIGNED_IMAGE=$(basename "$1" | sed 's/.bin$/.bin.rsa2048.signed/')

SIGNED_IMAGE_PATH=$(dirname "$FilePath")/"$SIGNED_IMAGE"
echo "SIGNED_IMAGE_PATH:$SIGNED_IMAGE_PATH"
#Delete SIGNED_IMAGE if exist
if [ -e "$SIGNED_IMAGE_PATH" ]; then
    rm "$SIGNED_IMAGE_PATH"
fi

#cd $FilePath
#cp $FileName.bin $FileName.bin.rsa2048.signed

cp $1 $1.rsa2048.signed

core_list="--iib core=0 type=0x0 image=$1 dlp=$2 to=$3 entry=$4 --psn 0x01 "
# Multi files need to be signed
#core_list+="--iib core=1 type=0x0 image=$1 dlp=$2 to=$3 entry=$3 --psn 0x01 "
# --iib with nohash
#core_list="--iib nohash core=0 type=0x0 image=$1 dlp=$2 to=$3 entry=$3 --psn 0x01 "

echo $core_list

$SIGN_CMD sign --v 2 --sec_ver 0x1234 --dgst sha256 --rcp key=$SIGNER_KEY $core_list --of $SIGNED_IMAGE

chmod 777 ./pactool
./pactool/pactool make_pac_image_no_gpt --output nvm.pac \
--allow_empty_partitions \
--product E3650 \
--da FDA:pactool/temp/nvm/FDA.bin \
--image 0x8000000:$SIGNED_IMAGE
#--image 0x8400000:temp/nvm/0x8000000.bin \
#--image 0x8800000:temp/nvm/0x8000000.bin \
#--image 0x8c00000:temp/nvm/0x8000000.bin \
#--image 0x9000000:temp/nvm/0x8000000.bin
#rm ${IMG_DIR}/${1}.elf.bin

#$BASE_DIR/atb_signer_e3 sign --v 2 --sec_ver 0x1234 --dgst sha256 ${core_list} --of ${IMG_DIR}/${1}.elf.bin
